package com.vip.jwt.common.utils.xcx.zfb;

import com.alipay.api.AlipayApiException;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.vip.jwt.common.utils.xcx.Constants;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Value;

/**
 * 支付宝授权工具类
 * https://opendocs.alipay.com/apis/api_9
 */
public class ZFBAuthUtil {

    @Getter
    private static String APP_ID;

    @Getter
    private static String PRIVATE_KEY;

    @Getter
    private static String PUBLIC_KEY;

    @Value("${zfb-xcx-appid}")
    public void setAppId(String appId) {
        APP_ID = appId;
    }

    @Value("${zfb-pay-private-key}")
    public void setPrivateKey(String privateKey){
        PRIVATE_KEY = privateKey;
    }

    @Value("${zfb-pay-public-key}")
    public void setPublicKey(String publicKey){
        PUBLIC_KEY = publicKey;
    }

    /**
     * 构造Client
     * @return
     */
    private static DefaultAlipayClient getCertAlipayRequest() throws AlipayApiException {
        String serverUrl = "https://openapi.alipay.com/gateway.do";
        CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
        certAlipayRequest.setServerUrl(serverUrl);
        certAlipayRequest.setAppId(APP_ID);
        certAlipayRequest.setPrivateKey(PRIVATE_KEY);
        certAlipayRequest.setFormat("json");
        certAlipayRequest.setCharset("utf-8");
        certAlipayRequest.setSignType(Constants.RSA2);
        DefaultAlipayClient defaultAlipayClient = new DefaultAlipayClient(certAlipayRequest);
        defaultAlipayClient.setAlipayPublicKey(PUBLIC_KEY);
        return defaultAlipayClient;
    }

    /**
     * 获取UserId
     * @return
     */
    public static String getUserInfo(String code) throws AlipayApiException {
        DefaultAlipayClient defaultAlipayClient = getCertAlipayRequest();
        AlipaySystemOauthTokenRequest tokenRequest = new AlipaySystemOauthTokenRequest();
        tokenRequest.setGrantType("authorization_code");
        tokenRequest.setCode(code);
        AlipaySystemOauthTokenResponse response = defaultAlipayClient.execute(tokenRequest);
        return response.getBody();
    }

}
